package com.wulinbus.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fancy.common.StoreFileTypeEnum;
import com.fancy.common.results.Results;
import com.fancy.common.utils.Config;
import com.fancy.common.utils.DateUtil;
import com.fancy.common.utils.StringUtil;
import com.wulinbus.model.CreativeLikeFlagModel;
import com.wulinbus.model.CreativeModel;
import com.wulinbus.model.UserModel;
import com.wulinbus.service.CreativeOrderService;
import com.wulinbus.service.CreativeService;
import com.wulinbus.service.FileStoreService;
import com.wulinbus.service.UserService;
import com.wulinbus.utils.CasUtil;

@Controller
public class CreativeController{
	@Resource
	private FileStoreService fileStoreService;
	@Resource
	private CreativeService creativeService;
	@Resource
	private CreativeOrderService creativeOrderService;
	@Resource
	private UserService userService;

	@RequestMapping("creative_publish.html")
	public String creative_publish(Model model,HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("userModel", userModel);
		model.addAttribute("uid", uid);
		return "page-creative-publish";
	}

	@RequestMapping("creative_buy.html")
	public String creative_buy(Model model, Integer cid, HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
		model.addAttribute("creativeModel", creativeModel);
		model.addAttribute("uid", uid);
		model.addAttribute("cid", cid);
		UserModel userModel = userService.findUserByUid(creativeModel.getUid());
		model.addAttribute("userModel", userModel);
		return "page-creative-buy";
	}

	@RequestMapping("creative_editor.html")
	public String creative_editor(Model model, Integer cid, HttpServletRequest request, Integer creative_uid) {
		String uid = CasUtil.getUid(request);
		CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
		List<String> urlList = creativeService.getUrlListByCid(cid);
		UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("creativeModel", creativeModel);
		model.addAttribute("urlList", urlList);
		model.addAttribute("uid", uid);
		model.addAttribute("userModel", userModel);
		return "page-creative-editor";
	}

	// @RequestMapping("search_work_success.html")
	// public String search_work_success(Model model, String search) {
	// List<Integer> uids = new ArrayList<Integer>();
	// List<CreativeModel> creativeList =
	// creativeService.findCreativeByTitle(search);
	// for (CreativeModel creativeModel : creativeList) {
	// uids.add(creativeModel.getUid());
	// }
	// List<UserModel> userList = userService.getListByUid(uids);
	// model.addAttribute("creativeList", creativeList);
	// model.addAttribute("userList", userList);
	// // System.err.println(userList.size());
	// return "page-creative-list";
	// }
	//
	// @RequestMapping("search_author_success.html")
	// public String search_author_success(Model model, String search) {
	// List<UserModel> userList = userService.findUserByKeyAuthor(search);
	// List<Integer> uids = userService.findUidByKeyAuthor(search);
	// List<CreativeModel> creativeList =
	// creativeService.findCreativeListByUids(uids);
	// model.addAttribute("userList", userList);
	// model.addAttribute("creativeList", creativeList);
	// return "page-creative-list";
	// }
	//
	// @RequestMapping("search_fail.html")
	// public String search_fail() {
	// return "page-search-fail";
	// }

	/**
	 * 上传图片 
	 */
	@RequestMapping(value = "image_upload.json", method = RequestMethod.POST)
	public void image_upload(String uploadflag,Model model, @RequestParam("imgFile") MultipartFile image, HttpServletResponse response) throws Exception {
		Results<String> fileUploadDO = fileStoreService.saveImage(uploadflag,image, StoreFileTypeEnum.IMAGES.toString());
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write("{\"error\": 0,\"url\":\"" + Config.getString("upload.file.host") + fileUploadDO.getObject() + "\"}");
	}

	/**
	 * 上传创意
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "creative_upload.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void creative_upload(Model model, HttpServletRequest request,
			HttpServletResponse response, String title, String cdescribe, Integer cvalue, String autro_instr, HttpSession session) throws Exception {
		response.setContentType("application/json;charset=UTF-8");
		String uid = CasUtil.getUid(request);
		String coverurl = request.getParameter("curl");
		String[] matterurl = request.getParameterValues("murl");
		String sourceurl = request.getParameter("surl");
		CreativeModel creativeModel_c = new CreativeModel();
		CreativeModel creativeModel_u = new CreativeModel();
		creativeModel_c.setUid(Integer.parseInt(uid));
		creativeModel_c.setTitle(title);
		creativeModel_c.setCdescribe(cdescribe);
		creativeModel_c.setCvalue(cvalue);
		creativeModel_c.setAutro_instr(autro_instr);
		creativeModel_c.setCover_url(coverurl);
		creativeModel_c.setSource_url(sourceurl);
		creativeService.addCreative(creativeModel_c);
		Integer cid = creativeModel_c.getCid();
		if (matterurl != null) {
			for (int i = 0; i < matterurl.length; i++) {
				creativeModel_u.setCid(cid);
				String matter_url = matterurl[i];
				creativeModel_u.setMatter_url(matter_url);
				creativeService.addCreativeUrl(creativeModel_u);
			}
		}
		response.getWriter().write("{\"success\":\"true\",\"cid\":\"" + cid + "\"}");
	}

	/**
	 * 编辑创意
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "creative_upload_editor.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void creative_upload_editor(HttpServletResponse response, String mids, Integer cid, CreativeModel creativeModel_post,
			 Model model, HttpServletRequest request) throws Exception {
		response.setContentType("application/json;charset=UTF-8");
		String uid = CasUtil.getUid(request);
		String coverurl = request.getParameter("curl");
		String[] matterurl = request.getParameterValues("murl");
		String sourceurl = request.getParameter("surl");
		creativeModel_post.setCid(cid);
		creativeModel_post.setUid(Integer.parseInt(uid));
		creativeModel_post.setCover_url(coverurl);
		creativeModel_post.setSource_url(sourceurl);
		String current_data = DateUtil.getCurDateYmd();
		creativeModel_post.setCurrent_data(current_data);
		creativeService.updateCreative(creativeModel_post);
		if (StringUtils.isNotBlank(mids)) {
			String[] midArr = mids.split(",");
			for (int i = 0; i < midArr.length; i++) {
				creativeService.deleteCreativeUrlByMid(Integer.parseInt(midArr[i]), cid);
			}
		}
		if (matterurl != null) {
			for (int i = 0; i < matterurl.length; i++) {
				creativeModel_post.setCid(cid);
				String matter_url = matterurl[i];
				creativeModel_post.setMatter_url(matter_url);
				creativeService.addCreativeUrl(creativeModel_post);
			}
		}

		response.getWriter().write("{\"success\":\"true\",\"cid\":\"" + cid + "\"}");
	}

	/**
	 * 创意列表
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "creative_list.html", method = { RequestMethod.GET, RequestMethod.POST })
	public String creative_list(Model model, @RequestParam(defaultValue = "8") Integer pageSize,
			@RequestParam(defaultValue = "1") Integer pageIndex,HttpServletRequest request, String keyword,
			String mids) {

		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		//
		List<CreativeModel> creativeList = new ArrayList<CreativeModel>();
		Integer totalCount = 0;
		List<Integer> midList = new ArrayList<Integer>();
		//
		if (!StringUtil.isEmpty(mids)) {
			String[] midTemp = mids.substring(1).split(",");
			if (midTemp.length > 0) {
				for (String mid : midTemp) {
					Integer midInt=Integer.parseInt(mid);
					midList.add(midInt);
				}
				creativeList = creativeService.findCreativeListByMids(midList);
				totalCount = creativeList.size();
			}
		} else {
			creativeList = creativeService.getCreativeList(keyword, start, pageSize);
			totalCount = creativeService.count(keyword);
		}
		//
		List<Integer> uids = new ArrayList<Integer>();
		for (CreativeModel creativeModel : creativeList) {
			uids.add(creativeModel.getUid());
		}
		if (uids.size() > 0) {
			List<UserModel> userList = userService.getListByUid(uids);
			model.addAttribute("userList", userList);
		}
		model.addAttribute("creativeList", creativeList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("uid", uid);
		model.addAttribute("keyword", keyword);
		if (StringUtils.isNotBlank(uid))
			model.addAttribute("user", userService.findUserByUid(Integer.parseInt(uid)));
		return "page-creative-list";
	}

	// /**
	// * 创意搜索
	// *
	// * @throws IOException
	// */
	// @RequestMapping(value = "creative_search.json", method = {
	// RequestMethod.POST, RequestMethod.GET })
	// public void creative_search(HttpServletResponse response,
	// HttpServletRequest request, String search) throws IOException {
	// response.setContentType("application/json;charset=UTF-8");
	// String search_type = request.getParameter("search_type");
	// if (search_type.equals("作品名")) {
	// List<CreativeModel> creativelist =
	// creativeService.findCreativeByTitle(search);
	// if (creativelist != null) {
	// response.getWriter().write("{\"search_work\":\"true\",\"search\":\"" +
	// search + "\"}");
	// } else {
	// response.getWriter().write("{\"search_work\":\"false\"}");
	// }
	// } else if (search_type.equals("作者名")) {
	// List<Integer> uids = userService.findUidByKeyAuthor(search);
	// List<CreativeModel> creativeList =
	// creativeService.findCreativeListByUids(uids);
	// if (creativeList != null) {
	// response.getWriter().write("{\"search_autor\":\"true\",\"search\":\"" +
	// search + "\"}");
	// } else {
	// response.getWriter().write("{\"search_autor\":\"false\"}");
	// }
	// }
	// }

	/**
	 * 创意作品详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "creative_detail.html", method = { RequestMethod.GET, RequestMethod.POST })
	public String creative_detail(Model model, Integer cid, HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		List<CreativeModel> creativeUrlList = creativeService.getCreativeUrlList(cid);
		CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
		UserModel userModel = userService.findUserByUid(creativeModel.getUid());
		List<CreativeModel> creativeList = creativeService.findCreativeByUidOnly(creativeModel.getUid());
		model.addAttribute("creativeList", creativeList);
		model.addAttribute("userModel", userModel);
		model.addAttribute("creativeUrlList", creativeUrlList);
		model.addAttribute("creativeModel", creativeModel);
		model.addAttribute("uid", uid);
		CreativeLikeFlagModel creativeLikeModel = creativeService.getCreativeLikeModel(cid, uid);
		if (creativeLikeModel != null && creativeLikeModel.getLikeflag()) {
			model.addAttribute("like_flag", 1);
		} else {
			model.addAttribute("like_flag", 0);
		}
		return "page-creative-detail";
	}

	/**
	 * 创意购买成功
	 * 
	 * @param model
	 * @param cid
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "creative_buy_suc.html", method = { RequestMethod.GET, RequestMethod.POST })
	public String creative_buy_suc(Model model, Integer cid, HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
			model.addAttribute("uid", uid);
			if (creativeOrderService.getOrderPayByUid(cid, Integer.parseInt(uid)) != null) {
				CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
				model.addAttribute("creativeModel", creativeModel);
				model.addAttribute("buy_flag", 1);
			} else {
				model.addAttribute("buy_flag", 0);
			}
			return "page-creative-buy-suc";
	}

	/**
	 * 创意作品点赞
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "creative_like.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void creative_like(HttpServletResponse response, Model model, Integer cid, HttpServletRequest request)
			throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		String uid = CasUtil.getUid(request);
		CreativeLikeFlagModel creativeLikeFlagModel = creativeService.getCreativeLikeModel(cid, uid);
		if (creativeLikeFlagModel == null) {
			creativeService.setLikeFlag(cid, uid);
			creativeService.like(cid);
			Integer addlike = creativeService.getLikeByCid(cid);
			response.getWriter().write("{\"success\":\"true\",\"addlike\":\"" + addlike + "\"}");
		}

	}
}
